package com.customization.unionpay.market.workflowaction;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.CloudFlashPaymentUtils;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.OverTimeSetBean;
import weaver.workflow.request.RequestManager;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author sjm
 * @description 营销事项申请表单节点(云闪付)action
 */
public class MarketingApplicationChangeYunAction implements Action {

    private static final Logger log = LoggerFactory.getLogger(MarketingApplicationChangeYunAction.class);

    @Override
    public String execute(RequestInfo requestInfo) {

        OverTimeSetBean overTimeBean = new OverTimeSetBean();

        RequestManager rm = requestInfo.getRequestManager();

        try {
            ResourceComInfo rci = new ResourceComInfo();
            SubCompanyComInfo subCompanyComInfo = new SubCompanyComInfo();

            int nodeId = rm.getNodeid();
            // 流程表单id
            int formId = rm.getFormid();

            int user = rm.getUser().getUID();                  // 当前操作者
            String tableName = rm.getBillTableName();          // 表单名称
            String requestId = requestInfo.getRequestid();     // 流程id

            String nbyxValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "zjly", "内部营销");
            log.info("内部营销枚举值：" + nbyxValue);
            String nwbyxValue = com.customization.unionpay.market.util.FormDataUtils.getItemValue(formId, "zjly", "内外部联合营销");
            log.info("内外部联合营销枚举值：" + nwbyxValue);

            Map<String, Object> allFormData = com.customization.unionpay.market.util.FormDataUtils.getAllFormData(requestInfo);

            Map<String, String> mainMap = (Map<String, String>) allFormData.get("mainMap");
            // 所有明细表的值
            Map<String, Map<String, Map<String, String>>> detailMap = (Map<String, Map<String, Map<String, String>>>) allFormData.get("detailMap");

            Map<String, Map<String, String>> dt1 = detailMap.get("dt1");

            String nodeName = overTimeBean.getNodeName(nodeId);
            log.info("nodeName："+nodeName);

            // 报账公司
            String bzgs = mainMap.get("bzgs");
            log.info("bzgs:" + bzgs);
            String subCompanyname = subCompanyComInfo.getSubCompanyname(bzgs);
            log.info("subCompanyname:" + subCompanyname);
            // 主 业务类型        ywlx
            String ywlx = mainMap.get("ywlx");
            String ywlxName = com.customization.unionpay.market.util.FormDataUtils.getItemName(formId,"ywlx",ywlx);
            log.info("业务类型："+ywlxName);

            String yxpthdsqm = mainMap.get("yxpthdsqm");
            log.info("yxpthdsqm："+yxpthdsqm);
            String zjly = mainMap.get("zjly");
            log.info("zjly："+zjly);
            String bcdzje = "";
            // 明细只有一行数据
            for (String key : dt1.keySet()) {
                Map<String, String> value = dt1.get(key);
                // 本次调整金额
                bcdzje = com.customization.unionpay.market.util.FormDataUtils.changeNumber(value.get("bcdzje"));
            }

            JSONObject changeDatas = new JSONObject();
            // 调整原因	     data.adjustReason	String	1024		必填
            changeDatas.put("adjustReason", yxpthdsqm+"调整金额");
            // 调整类型	     data.adjustType	String	1		        必填    0-增加  1-减少  2-退款
            if("营销平台事项申请金额调增单".equals(ywlxName)) {
                changeDatas.put("adjustType", "0");
            }else if("营销平台事项申请金额调减单".equals(ywlxName)) {
                changeDatas.put("adjustType", "1");
            }
            // 银联出资调整金额 data.adjustUnionpayValue	decimal(12,2) 必填。 内外联合类型的预算授权码该值不能大于调整金额的值。非内外联合类型的预算授权码该值该值传递0
            if(zjly.equals(nbyxValue)){
                changeDatas.put("adjustUnionpayValue", "0");
            }else if(zjly.equals(nwbyxValue)){
                changeDatas.put("adjustUnionpayValue", bcdzje);
            }
            // 调整金额	     data.adjustValue	decimal(12,2)			必填
            changeDatas.put("adjustValue", bcdzje);
            // 待审核资金量	 data.fundValue				必填      该值为已审核资金量值加上调整金额的量
            changeDatas.put("fundValue", "");
            // 预算授权码	     data.budgetAuthCode	String	30		必填
            changeDatas.put("budgetAuthCode",yxpthdsqm);

            // 本次调整金额
            Double bcdzjeD = new BigDecimal(bcdzje).doubleValue();
            log.info("bcdzjeD:" + bcdzjeD);

            // 调用云闪付,动作失败回退指定节点 奖励金算立减  （立减，积分（普通），积分（消费送红包），奖励金）
            // 分公司
            if(!subCompanyname.contains("总公司")) {
                log.info("进入分公司");
                if ("核算会计初审".equals(nodeName)) {
                    // fundValueChecked-剩余资金量 +/-  bcdzje    nbczje
                    List<String> codes = new ArrayList<>();
                    codes.add(yxpthdsqm);
                    // 云闪付查询
                    try {
                        String resultStr = CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(codes);
                        log.info("云闪付查询返回参数：" + resultStr);
                        JSONObject resultJson = JSONObject.parseObject(resultStr);
                        String errorMessage = resultJson.getString("errorMessage");
                        if ("成功".equals(errorMessage)) {
                            JSONArray data = resultJson.getJSONArray("data");
                            log.info("解析data参数：" + data);
                            if (data.size() > 0) {
                                JSONObject single = data.getJSONObject(0);
                                // 剩余资金
                                Double fundValueChecked = single.getDouble("fundValueChecked");
                                Double nbje = Double.valueOf(bcdzje);

                                if ("营销平台事项申请金额调增单".equals(ywlxName)) {
                                    String fundValue = com.customization.unionpay.market.util.FormDataUtils.changeNumber(String.valueOf((fundValueChecked + nbje)));
                                    changeDatas.put("fundValue", fundValue);
                                } else if ("营销平台事项申请金额调减单".equals(ywlxName)) {
                                    String fundValue = com.customization.unionpay.market.util.FormDataUtils.changeNumber(String.valueOf((fundValueChecked - nbje)));
                                    changeDatas.put("fundValue", fundValue);
                                }
                                // 云闪付调整
                                try {
                                    String innerAdjustByBudgetCode = CloudFlashPaymentUtils.innerAdjustByBudgetCode(changeDatas);
                                    log.info("云闪付调整返回参数：" + innerAdjustByBudgetCode);
                                    JSONObject innerAdjustByBudgetCodeJson = JSONObject.parseObject(innerAdjustByBudgetCode);
                                    String innerAdjustErrorMessage = innerAdjustByBudgetCodeJson.getString("errorMessage");
                                    if ("成功".equals(innerAdjustErrorMessage)) {

                                    } else {
                                        log.error("云闪付调整失败：" + resultJson.getString("errorCode") + "----" + innerAdjustErrorMessage);
                                        com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(innerAdjustErrorMessage, tableName, requestId);
//                                        FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                                        requestInfo.getRequestManager().setMessageid("10001");
                                        requestInfo.getRequestManager().setMessagecontent(innerAdjustErrorMessage);
                                        return Action.FAILURE_AND_CONTINUE;
                                    }
                                } catch (Exception e) {
                                    log.error("云闪付调整异常：" + e.getMessage());
                                    com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(e.getMessage(), tableName, requestId);
//                                    FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                                    requestInfo.getRequestManager().setMessageid("10001");
                                    requestInfo.getRequestManager().setMessagecontent(e.getMessage());
                                    return Action.FAILURE_AND_CONTINUE;
                                }
                            } else {
                                // 云闪付查询失败
                                log.error("yunSelectErrorCode: 云闪付根据授权码查询为空");
                                com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo("云闪付根据授权码查询为空", tableName, requestId);
//                                FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                                requestInfo.getRequestManager().setMessageid("10001");
                                requestInfo.getRequestManager().setMessagecontent("云闪付根据授权码查询为空");
                                return Action.FAILURE_AND_CONTINUE;
                            }
                        } else {
                            log.error("云闪付查询失败：" + resultJson.getString("errorCode") + "----" + errorMessage);
                            com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(errorMessage, tableName, requestId);
//                            FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                            requestInfo.getRequestManager().setMessageid("10001");
                            requestInfo.getRequestManager().setMessagecontent(errorMessage);
                            return Action.FAILURE_AND_CONTINUE;
                        }
                    } catch (Exception e) {
                        log.error("云闪付查询异常：" + e.getMessage());
                        com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(e.getMessage(), tableName, requestId);
//                        FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                        requestInfo.getRequestManager().setMessageid("10001");
                        requestInfo.getRequestManager().setMessagecontent(e.getMessage());
                        return Action.FAILURE_AND_CONTINUE;
                    }
                }
            }else {
                // 总公司
                log.info("进入总公司");
                if (bcdzjeD > 100000) {
                    // 项目金额 > 100000
                    if ("公司分管财务领导审批".equals(nodeName)) {
                        // fundValueChecked-剩余资金量 +/-  bcdzje    nbczje
                        List<String> codes = new ArrayList<>();
                        codes.add(yxpthdsqm);
                        // 云闪付查询
                        try {
                            String resultStr = CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(codes);
                            log.info("云闪付查询返回参数：" + resultStr);
                            JSONObject resultJson = JSONObject.parseObject(resultStr);
                            String errorMessage = resultJson.getString("errorMessage");
                            if ("成功".equals(errorMessage)) {
                                JSONArray data = resultJson.getJSONArray("data");
                                log.info("解析data参数：" + data);
                                if (data.size() > 0) {
                                    JSONObject single = data.getJSONObject(0);
                                    // 剩余资金
                                    Double fundValueChecked = single.getDouble("fundValueChecked");
                                    Double nbje = Double.valueOf(bcdzje);
                                    if ("营销平台事项申请金额调增单".equals(ywlxName)) {
                                        String fundValue = com.customization.unionpay.market.util.FormDataUtils.changeNumber(String.valueOf((fundValueChecked + nbje)));
                                        changeDatas.put("fundValue", fundValue);
                                    } else if ("营销平台事项申请金额调减单".equals(ywlxName)) {
                                        String fundValue = com.customization.unionpay.market.util.FormDataUtils.changeNumber(String.valueOf((fundValueChecked - nbje)));
                                        changeDatas.put("fundValue", fundValue);
                                    }
                                    // 云闪付调整
                                    try {
                                        String innerAdjustByBudgetCode = CloudFlashPaymentUtils.innerAdjustByBudgetCode(changeDatas);
                                        log.info("云闪付调整返回参数：" + innerAdjustByBudgetCode);
                                        JSONObject innerAdjustByBudgetCodeJson = JSONObject.parseObject(innerAdjustByBudgetCode);
                                        String innerAdjustErrorMessage = innerAdjustByBudgetCodeJson.getString("errorMessage");
                                        if ("成功".equals(innerAdjustErrorMessage)) {

                                        } else {
                                            log.error("云闪付调整失败：" + resultJson.getString("errorCode") + "----" + innerAdjustErrorMessage);
                                            com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(innerAdjustErrorMessage, tableName, requestId);
                                            com.customization.unionpay.market.util.FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                                        }
                                    } catch (Exception e) {
                                        log.error("云闪付调整异常：" + e.getMessage());
                                        com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(e.getMessage(), tableName, requestId);
                                        com.customization.unionpay.market.util.FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                                    }
                                } else {
                                    // 云闪付查询失败
                                    log.error("yunSelectErrorCode: 云闪付根据授权码查询为空");
                                    com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo("云闪付根据授权码查询为空", tableName, requestId);
                                    com.customization.unionpay.market.util.FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                                }
                            } else {
                                log.error("云闪付查询失败：" + resultJson.getString("errorCode") + "----" + errorMessage);
                                com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(errorMessage, tableName, requestId);
                                com.customization.unionpay.market.util.FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                            }
                        } catch (Exception e) {
                            log.error("云闪付查询异常：" + e.getMessage());
                            com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(e.getMessage(), tableName, requestId);
                            com.customization.unionpay.market.util.FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                        }
                    }
                } else {
                    // 项目金额 < 100000
                    if ("财务部总经理室审批".equals(nodeName)) {
                        // fundValueChecked-剩余资金量 +/-  bcdzje    nbczje
                        List<String> codes = new ArrayList<>();
                        codes.add(yxpthdsqm);
                        // 云闪付查询
                        try {
                            String resultStr = CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(codes);
                            log.info("云闪付查询返回参数：" + resultStr);
                            JSONObject resultJson = JSONObject.parseObject(resultStr);
                            String errorMessage = resultJson.getString("errorMessage");
                            if ("成功".equals(errorMessage)) {
                                JSONArray data = resultJson.getJSONArray("data");
                                log.info("解析data参数：" + data);
                                if (data.size() > 0) {
                                    JSONObject single = data.getJSONObject(0);
                                    // 剩余资金
                                    Double fundValueChecked = single.getDouble("fundValueChecked");
                                    Double nbje = Double.valueOf(bcdzje);

                                    if ("营销平台事项申请金额调增单".equals(ywlxName)) {
                                        String fundValue = com.customization.unionpay.market.util.FormDataUtils.changeNumber(String.valueOf((fundValueChecked + nbje)));
                                        changeDatas.put("fundValue", fundValue);
                                    } else if ("营销平台事项申请金额调减单".equals(ywlxName)) {
                                        String fundValue = com.customization.unionpay.market.util.FormDataUtils.changeNumber(String.valueOf((fundValueChecked - nbje)));
                                        changeDatas.put("fundValue", fundValue);
                                    }
                                    // 云闪付调整
                                    try {
                                        String innerAdjustByBudgetCode = CloudFlashPaymentUtils.innerAdjustByBudgetCode(changeDatas);
                                        log.info("云闪付调整返回参数：" + innerAdjustByBudgetCode);
                                        JSONObject innerAdjustByBudgetCodeJson = JSONObject.parseObject(innerAdjustByBudgetCode);
                                        String innerAdjustErrorMessage = innerAdjustByBudgetCodeJson.getString("errorMessage");
                                        if ("成功".equals(innerAdjustErrorMessage)) {

                                        } else {
                                            log.error("云闪付调整失败：" + resultJson.getString("errorCode") + "----" + innerAdjustErrorMessage);
                                            com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(innerAdjustErrorMessage, tableName, requestId);
                                            com.customization.unionpay.market.util.FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                                        }
                                    } catch (Exception e) {
                                        log.error("云闪付调整异常：" + e.getMessage());
                                        com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(e.getMessage(), tableName, requestId);
                                        com.customization.unionpay.market.util.FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                                    }
                                } else {
                                    // 云闪付查询失败
                                    log.error("yunSelectErrorCode: 云闪付根据授权码查询为空");
                                    com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo("云闪付根据授权码查询为空", tableName, requestId);
                                    com.customization.unionpay.market.util.FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                                }
                            } else {
                                log.error("云闪付查询失败：" + resultJson.getString("errorCode") + "----" + errorMessage);
                                com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(errorMessage, tableName, requestId);
                                com.customization.unionpay.market.util.FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                            }
                        } catch (Exception e) {
                            log.error("云闪付查询异常：" + e.getMessage());
                            com.customization.unionpay.market.util.FormDataUtils.changeErrorInfo(e.getMessage(), tableName, requestId);
                            FormDataUtils.rejectRequest(Integer.parseInt(requestId), user);
                        }
                    }
                }
            }
        } catch (Exception e) {
            // 异常报错是填写异常信息，阻止流程继续流转
            requestInfo.getRequestManager().setMessageid("10001");
            requestInfo.getRequestManager().setMessagecontent(e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }
}
